﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using Timer = System.Timers.Timer;

namespace MT.CustomUserControl.Views
{
    /// <summary>
    /// DateAndTimerUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class DateAndTimerUserControl : UserControl
    {
        private Timer DateAndTimeUpdateTimer = new Timer();

        public DateAndTimerUserControl()
        {
            InitializeComponent();

            DateAndTimeUpdateTimer.Interval = 600;//1分钟更新一次
            DateAndTimeUpdateTimer.Enabled = true;
            DateAndTimeUpdateTimer.Elapsed += DateAndTimeUpdateTimer_Elapsed;
            DateAndTimeUpdateTimer.Start();
        }

        private void DateAndTimeUpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                Application.Current?.Dispatcher.Invoke(() =>
                {
                    string dateTime = DateTime.Now.ToString("yyyy-MM-dd");
                    string week = DateTime.Now.ToString("dddd", new CultureInfo("zh-cn"));
                    string hour = DateTime.Now.ToString("HH:mm");
                    textBlock_Day.Text = dateTime;
                    textBlock_Week.Text = week;
                    textBlock_Time.Text = hour;
                });
            }
            catch (TaskCanceledException ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        public void CloseUserControl()
        {
            DateAndTimeUpdateTimer.Stop();
        }
    }
}
